package com.svpino.netflix;

import java.util.HashMap;
import java.util.Map.Entry;

import com.svpino.netflix.model.Catalog;

public class CatalogContext {

	private final Proxy proxy;
	private final HashMap<String, String> parameters;

	public CatalogContext(Proxy proxy) {
		this.proxy = proxy;
		this.parameters = new HashMap<String, String>();
	}

	public CatalogContext expand(Branch branch) {
		String value = branch.getIdentifier();
		if (this.parameters.containsKey("expand")) {
			value = this.parameters.remove("expand") + "," + value;
		}

		this.parameters.put("expand", value);
		return this;
	}

	public CatalogContext start(int value) {
		this.parameters.put("start_index", new Integer(value).toString());
		return this;
	}

	public CatalogContext take(int value) {
		this.parameters.put("max_results", new Integer(value).toString());
		return this;
	}

	public Catalog search(String term) throws Exception {
		this.parameters.remove("term");
		this.parameters.put("term", term);

		return this.proxy.getCatalogParser().parse(getUrl(Constants.RESOURCE_CATALOG_TITLES));
	}

	private String getUrl(String baseUrl) {
		String url = baseUrl;
		for (Entry<String, String> parameter : this.parameters.entrySet()) {
			url += url.contains("?") ? "&" : "?";
			url += parameter.getKey() + "=" + parameter.getValue();
		}

		return url;
	}
}
